package com.chlitina.store.modules.sys.security;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chlitina.store.common.session.BoTongSessionContext;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;

public class LoginFormAuthenticationFilter extends FormAuthenticationFilter {  
    private static final Logger LOG = LoggerFactory.getLogger(LoginFormAuthenticationFilter.class);  
      
    public LoginFormAuthenticationFilter() {  
    }  
    
    @Override  
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }
        try {
        	
        	HttpServletRequest httpRequest = (HttpServletRequest)request;
        	String loginName = httpRequest.getParameter(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        	String password = httpRequest.getParameter(FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);
        	String sessionId = httpRequest.getSession().getId();
    		String allowLogin = StoreUtils.isAllowLogin(loginName, password, sessionId);
    		if (!"true".equals(allowLogin)) {
    			throw new IncorrectCaptchaException(allowLogin); 
			}
    		Subject subject = getSubject(request, response);
    		subject.login(token);
            return onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException e) {
        	if(!(e instanceof IncorrectCaptchaException)) {
        		e = new AuthenticationException("密码输入错误");
        	}
            return onLoginFailure(token, e, request, response);
        }
    }
    
    //保存异常对象到request  
    @Override  
    protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
        String className = ae.getMessage();
        request.setAttribute(getFailureKeyAttribute(), className);
    }
}
    
    
  
